package com.util;

import javax.servlet.http.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;



public class UserCookie {
	private static final Log logger = LogFactory.getLog

	(UserCookie.class);

	private static final String PASS_USERNAME_KEY =

	"PASS_USERNAME";

	private static final String PASS_USER_PASSWORD_KEY =

	"PASS_USERPASSWD";

	private HttpServletRequest request;

	private HttpServletResponse response;

	private String username;

	public String getUsername() {
		return username;
	}

	public UserCookie(HttpServletRequest request,

	HttpServletResponse response) {
		username = "";
		this.request = request;
		this.response = response;
		getCookies();
	}

	public void addC(String name, String value) {
		Cookie cookies = new Cookie(name, value);
		cookies.setPath("/");
		cookies.setSecure(false);
		cookies.setVersion(0);
		cookies.setMaxAge(-1);
		cookies.setDomain(".fantong.com");
		response.addCookie(cookies);
	}

	public void addC(String name, String value, int maxage) {
		Cookie cookies = new Cookie(name, value);
		cookies.setPath("/");
		cookies.setMaxAge(maxage);
		cookies.setDomain(".fantong.com");
		response.addCookie(cookies);
	}

	public void addCookies(String username) {
		this.username = username;
		addC(PASS_USERNAME_KEY, username);
	}

	private void getCookies() {
		Cookie cookies[] = request.getCookies();
		Cookie sCookie = null;
		try {
			if (cookies != null && cookies.length > 0) {
				for (int i = 0; i < cookies.length; i++) {
					sCookie = cookies[i];
					if (!sCookie.getName().equalsIgnoreCase(PASS_USERNAME_KEY))
						continue;
					this.username = Escape.unescape(sCookie.getValue());
					break;
				}

			}
		} catch (Exception ex) {
			logger.error(ex);
		}
	}

	public void removeCookie() {
		addC("PASS_USERNAME", "", 0);
	}

}
